#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/22
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import json, session
from project.define import AxiosMessage, PermissionsModule
from project.modules import Role, User, CarParkSetting, CarParkPlace, CarParkRule

class Messager(AxiosMessage):
    """
    消息管理器
    """
    def __init__(self) -> None:
        super().__init__()
        self.__view_names = {"setting":"車場設置","place":"車位","user":"收費員","rule":"收費規則"}
        self.user_role = Role.query.filter_by(Name="user").first()

    def __get_data(self, view, **data):
        """
        获取数据
        """
        r = None
        if view == "place":
            r = CarParkPlace.selected_data(**data)
        elif view == 'user':
            r = User.selected_data(**data)
        elif view == "rule":
            r = CarParkRule.selected_data(**data)
        if r:
            return self.json_data(**r.to_dict())
        return "Fail"

    def __reset_filter(self, view):
        """
        重置条件
        """
        if view == "place":
            filter_name = "PlaceFilter"
        elif view == "user":
            filter_name= "CarParkUserFilter"
        elif view == "rule":
            filter_name= "CarParkRuleFilter"
        filters = session.get(filter_name)
        if filters:
            del session[filter_name]
        return "OK"

    def __set_filter(self, view, **data):
        """
        设置条件
        """
        if view == "place":
            session['PlaceFilter'] = data
        elif view == "user":
            session['CarParkUserFilter'] = data
        elif view == "rule":
            session['CarParkRuleFilter'] = data
        return "OK"

    def __delete_data(self, view, **data):
        """
        删除数据
        """
        data_name = self.__view_names.get(view)
        if data_name:
            if view == "place":
                ret = CarParkPlace.delete_data(**data)
            elif view == "rule":
                ret = CarParkRule.delete_data(**data)
            elif view == "user":
                ret = User.delete_data(**data)
        if ret:
            return self.success(f"{data_name}刪除成功")
        return self.warning(f"{data_name}刪除失敗")
        
    def __modify_data(self, view, **data):
        """
        修改数据
        """
        data_name = self.__view_names.get(view)
        if data_name:
            if view == "place":
                ret = CarParkPlace.modify_data(**data)
            elif view == "rule":
                ret = CarParkRule.modify_data(**data)
            elif view == "setting":
                ret = CarParkSetting.modify_data(**data)
            elif view == "user":
                ret = User.insert_data(**data)
        if ret:
            if isinstance(ret, dict):
                return self.success(f"{data_name}更新成功")
            elif ret == "ignore":
                return self.warning(f"{data_name}沒有更新")
        return self.warning(f"{data_name}更新失敗")

    def __insert_data(self, view, **data):
        """
        插入数据
        """
        data_name = self.__view_names.get(view)
        if data_name:
            if view == "place":
                if CarParkPlace.place_exists(**data):
                    return self.warning("車位類型已存在")
                ret = CarParkPlace.insert_data(**data)
            elif view == "rule":
                if CarParkRule.check_exists(**data):
                    return self.warning("收費規則已存在")
                ret = CarParkRule.insert_data(**data)
            elif view == "user":
                data['RoleID'] = self.user_role.id
                ret = User.insert_data(**data)
        if ret:
            return self.success(f"新增{data_name}成功")
        return self.warning(f"新增{data_name}失敗")

    def post_data_handler(self, **kwargs):
        """
        POST数据处理
        """
        view = kwargs.get("View")
        for k, v in kwargs.items():
            if k == "Insert":
                return self.__insert_data(view, **v)
            elif k == "Modify":
                return self.__modify_data(view, **v)
            elif k == "Delete":
                return self.__delete_data(view, **v)
            elif k == "SetFilter":
                return self.__set_filter(view, **v)
            elif k == "ResetFilter":
                return self.__reset_filter(view)
            elif k == "GetData":
                return self.__get_data(view, **v)
        return self.error("請求錯誤，請聯係管理員")
        
    def __generate_page_data(self, *args):
        """
        生成页面数据
        """
        return {
            "ColumnName":args[0], 
            "ColumnNameJSON": json.dumps(args[0],ensure_ascii=False), 
            "TableDatas": args[1],
            "Filters": args[2],
            "FiltersJSON": json.dumps(args[2],ensure_ascii=False),
        }

    def ____form_page_data(self, *args):
        """
        表单页面数据
        """
        return {
            "ColumnName":args[0], 
            "ColumnNameJSON": json.dumps(args[0],ensure_ascii=False), 
            "SettingFormData": json.dumps(args[1],ensure_ascii=False)
        }

    def rule_page_data(self):
        """
        规则页面
        """
        filters = session.get("CarParkRuleFilter")
        if not filters:
            filters = dict.fromkeys(("VehicleType","Price"))
        data_filters = CarParkRule.generate_filters(**filters)
        if len(data_filters) == 0:
            table_datas = CarParkRule.query.all()
        else:
            table_datas = CarParkRule.query.filter(*data_filters).all()
        column_name = CarParkRule.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def user_page_data(self):
        """
        收费员页面
        """
        filters = session.get("CarParkUserFilter")
        if not filters:
            filters = dict.fromkeys(("CashierName","LoginName","Phone"))
        table_datas = User.query.filter_by(RoleID=self.user_role.id).all()
        column_name = User.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def place_page_data(self):
        """
        车位页面
        """
        filters = session.get("PlaceFilter")
        if not filters:
            filters = dict.fromkeys(("VehicleType","ParkingType","ParkingMethods"))
        data_filters = CarParkPlace.generate_filters(**filters)
        if len(data_filters) == 0:
            table_datas = CarParkPlace.query.all()
        else:
            table_datas = CarParkPlace.query.filter(*data_filters).all()
        column_name = CarParkPlace.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def setting_page_data(self):
        """
        闸机页面
        """
        setting = CarParkSetting.query.first()
        column_name = CarParkSetting.columns_name()
        return self.____form_page_data(*[column_name, setting.to_dict()])
